<?php
/**
 * Created by PhpStorm.
 * User: zhao shou qiang
 * Date: 2017/12/14 0014
 * Time: 11:50
 */

namespace backend\controllers;

use backend\models\PackageInitiationPlan;
use common\models\Country;
use common\models\MyPager;
use common\models\Package;
use common\models\Project;
use common\models\ProjectTeam;
use common\models\ProjectLike;
use common\models\UserModel;
use Yii;
use common\models\ProjectLog;
use common\models\ProjectUpdateLog;
use common\models\Responses;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;

class ProjectLogController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return parent::behaviors();
    }

    /**
     * 项目日志
     * @return string
     */
    public function actionIndex()
    {
        //$userId = Yii::$app->user->id;
        $projectId = Yii::$app->request->get('project_id');
        $packageId = Yii::$app->request->get('package_id');

        /**--------------------------  头部信息start --------------------------------**/
        //项目详情
        $project = Project::findOne($projectId);

        $data['Id'] = $projectId;
        $data['package_id'] = $packageId;
        $data['mortgage_id'] = intval(\Yii::$app->request->get('mortgage_id', 1));
        $data = Project::getProjectInfoData($data);
        //$data['data']['res']['provinceData'] = SearchPackage::getProvinces('pid=0');
        //所有部门人员
        $userModel = new UserModel();
        $where = ['not in', 'department',
            ['总裁办', '风控管理中心', '财务部', '技术部', '品牌部', '新大唐学院', '人力行政部',
                'ceooffice', 'windControlManagementCenter', 'finance', 'technology', 'brand', 'college', 'humanAdministration','',
            ]];
        $data['data']['res']['Base']['departments'] = $userModel->getDepartmentUsers($where);
        $data['data']['res']['Base']['access_users_ids'] = $data['data']['res']['Base']['access_users'] != "" ? explode(",", $data['data']['res']['Base']['access_users']) : "";
        $data['data']['res']['Base']['access_users'] = $this->getAccessUsers($data['data']['res']['Base']['access'], $data['data']['res']['Base']['access']);


        $data['data']['res']['user'] = (new \yii\db\Query())->select('*')->from('user')->all();
        $data['data']['res']['userChief'] = (new \yii\db\Query())->select('*')->from('user')->andWhere(['=', 'is_leader',1])->all();


        //是否关注
        $data_like = ProjectLike::find()->where(['project_id' => $data['data']['res']['Base']['id'], 'type' => 1, 'user_id' => Yii::$app->user->id])->asArray()->one();
        if ($data_like['id']) {
            $data['data']['res']['Base']['flow'] = 1;
        } else {
            $data['data']['res']['Base']['flow'] = 0;
        }
        //是否亮点
        $data_like = ProjectLike::find()->where(['project_id' => $data['data']['res']['Base']['id'], 'type' => 2, 'user_id' => Yii::$app->user->id])->asArray()->one();
        if ($data_like['id']) {
            $data['data']['res']['Base']['light_spot'] = 1;
        } else {
            $data['data']['res']['Base']['light_spot'] = 0;
        }
        //获取配置团队成员信息
        $teamZJ = array_column($data['data']['res']['teamZJ'], 'id');
        $teamFZR = array_column($data['data']['res']['teamFZR'], 'id');
        $teamXZR = array_column($data['data']['res']['teamXZR'], 'id');

//        $teamS = array_merge($teamZJ, $teamFZR, $teamXZR);
//        $data['data']['res']['teamInfo'] = Project::getTeamUserData($teamS);

        $data['data']['res']['teamInfo']['teamZJ'] = array();
        $data['data']['res']['teamInfo']['teamFZR'] = array();
        $data['data']['res']['teamInfo']['teamXZR'] = array();
        $getDepartmentUsersList = (new UserModel())->getDepartmentUsersList();

        if (!empty($teamZJ)) {
            foreach ($teamZJ as $value) {
                if (isset($getDepartmentUsersList[$value])) {
                    $teamZJ_array['id'] = $getDepartmentUsersList[$value]['id'];
                    $teamZJ_array['realname'] = $getDepartmentUsersList[$value]['realname'];
                    $teamZJ_array['username'] = $getDepartmentUsersList[$value]['username'];
                    $teamZJ_array['department'] = $getDepartmentUsersList[$value]['description'];
                    $teamZJ_array['avatar'] = $getDepartmentUsersList[$value]['avatar'];
                    $teamZJ_array['role'] = '项目总监';
                    $data['data']['res']['teamInfo']['teamZJ'][] = $teamZJ_array;
                }
            }
        }

        if (!empty($teamFZR)) {
            foreach ($teamFZR as $value) {
                if (isset($getDepartmentUsersList[$value])) {
                    $teamFZR_array['id'] = $getDepartmentUsersList[$value]['id'];
                    $teamFZR_array['realname'] = $getDepartmentUsersList[$value]['realname'];
                    $teamFZR_array['username'] = $getDepartmentUsersList[$value]['username'];
                    $teamFZR_array['department'] = $getDepartmentUsersList[$value]['description'];
                    $teamFZR_array['avatar'] = $getDepartmentUsersList[$value]['avatar'];
                    $teamFZR_array['role'] = '项目经理';
                    $data['data']['res']['teamInfo']['teamFZR'][] = $teamFZR_array;
                }
            }
        }

        if (!empty($teamXZR)) {
            foreach ($teamXZR as $value) {
                if (isset($getDepartmentUsersList[$value])) {
                    $teamXZR_array['id'] = $getDepartmentUsersList[$value]['id'];
                    $teamXZR_array['realname'] = $getDepartmentUsersList[$value]['realname'];
                    $teamXZR_array['username'] = $getDepartmentUsersList[$value]['username'];
                    $teamXZR_array['department'] = $getDepartmentUsersList[$value]['description'];
                    $teamXZR_array['avatar'] = $getDepartmentUsersList[$value]['avatar'];
                    $teamXZR_array['role'] = '团队成员';
                    $data['data']['res']['teamInfo']['teamXZR'][] = $teamXZR_array;
                }
            }
        }

        //项目所属资产包
        $packageInfo = Package::findOne($packageId);
        if (!empty($packageInfo)) {
            $data['data']['res']['packageName'] = $packageInfo->title;
            $data['data']['res']['Base']['code'] = $packageInfo->code;
            $province = '';
            $city = '';
            $country = new Country();
            if ($packageInfo->province > 0) {
                $province = $country->getName($packageInfo->province);
            }
            if ($packageInfo->city > 0) {
                $city = $country->getName($packageInfo->city);
            }
            $data['data']['res']['Base']['country'] = $province . $city;
        } else {
            $data['data']['res']['packageName'] = '';
            $data['data']['res']['Base']['code'] = '';
            $data['data']['res']['Base']['country'] = '';
        }
        /**--------------------------  头部信息end --------------------------------**/

        //当前页
        $page = Yii::$app->request->post('page', 1);

        //项目日志
        $projectLog = new ProjectLog();
        $projectLogs = $projectLog->getList($projectId);

        //项目更新日志
        $projectUpdateLog = new ProjectUpdateLog();
        $projectUpdateLogUsers = $projectUpdateLog->getUsers();

        if($project->type == 2) {
            $type = 2;
        } else {
            $type = 1;
        }
        $modules = $projectUpdateLog->getModuleArrayTitle($type);
        $count = $projectUpdateLog->getCount($projectId, 2, null, null, $type);

        $offset = 20;//默认每页显示条数
        $date = 2;//默认一月内
        $projectUpdateLogs = $projectUpdateLog->getList($projectId, $date, null, null, $type, $offset, ($page - 1) * $offset);
        //分页显示
        $param = array(
            'total_rows' => $count,
            'list_rows' => $offset, //每页显示条数
            'sub_pages' => 10, //预定显示页数
            'page_name' => 'page',
            'now_page' => $page,
        );
        $myPager = new MyPager($param);
        $pager = $myPager->contsruct_num_Page();

        $data['data']['res']['team'] = (new \yii\db\Query())->from(ProjectTeam::tableName())->select('*')->where(['=', 'project_id', $projectId])->one();
        if (!empty($projectInfoData['team'])) {
            //通过id获取总监名称
            $leaderIdArr = [];
            if (!empty($projectInfoData['team']['manager']) && preg_match('/,/', $projectInfoData['team']['manager'])) {
                $leaderIdArr = array_unique(explode(',', $projectInfoData['team']['manager']));
            } else if (is_string($projectInfoData['team']['manager'])) {
                $leaderIdArr = $projectInfoData['team']['manager'];
            }
            $leader_name = (new \yii\db\Query())->select('id,realname,department')->from(UserModel::tableName())->where(['in', 'id', $leaderIdArr])->all();
            $data['data']['res']['teamZJ'] = PackageInitiationPlan::pieceUsername($leader_name);
            //通过id获取负责人名称
            $ownerIdArr = [];
            if (!empty($projectInfoData['team']['owner']) && preg_match('/,/', $projectInfoData['team']['owner'])) {
                $ownerIdArr = array_unique(explode(',', $projectInfoData['team']['owner']));
            } else if (is_string($projectInfoData['team']['owner'])) {
                $ownerIdArr = $projectInfoData['team']['owner'];
            }
            $owner_name = (new \yii\db\Query())->select('id,realname,department')->from(UserModel::tableName())->where(['in', 'id', $ownerIdArr])->all();
            $data['data']['res']['teamFZR'] = PackageInitiationPlan::pieceUsername($owner_name);
            //通过id获取协助人
            $partnerIdArr = [];
            if (!empty($projectInfoData['team']['partner']) && preg_match('/,/', $projectInfoData['team']['partner'])) {
                $partnerIdArr = array_unique(explode(',', $projectInfoData['team']['partner']));
            } else if (is_string($projectInfoData['team']['partner'])) {
                $partnerIdArr = $projectInfoData['team']['partner'];
            }
            $partner_name = (new \yii\db\Query())->select('id,realname,department')->from(UserModel::tableName())->where(['in', 'id', $partnerIdArr])->all();
            $data['data']['res']['teamXZR'] = PackageInitiationPlan::pieceUsername($partner_name);
        } else {
            $data['data']['res']['teamZJ'] = [];
            $data['data']['res']['teamFZR'] = [];
            $data['data']['res']['teamXZR'] = [];
        }

        //$this->layout = false;
        return $this->render('index', [
            'projectLogs' => $projectLogs,
            'modules' => $modules,
            'projectUpdateLogUsers' => $projectUpdateLogUsers,
            'topData' => $data['data']['res'],
            'projectModel' => $project,
            //项目修改记录日志
            'data' => [
                'count' => $count,
                'data' => $projectUpdateLogs,
                'page' => $page,
                'pager' => $pager,
                'project_id' => $projectId,
                'package_id' => $packageId
            ]
        ]);
    }

    /**
     * ajax分页
     * @return array
     */
    public function actionPage()
    {
        if (Yii::$app->request->isAjax) {
            $projectId = (int)Yii::$app->request->post('project_id');
            $project = Project::findOne($projectId);
            if ($project->type == 2) {
                $type = 2;
            } else {
                $type = 1;
            }
            //$type = Yii::$app->request->post('type', 1);//module类型
            $page = Yii::$app->request->post('page', 1);//当前页
            $pageSize = Yii::$app->request->post('pageSize', 20);//每页条数

            $module = Yii::$app->request->post('module') ? (int)Yii::$app->request->post('module') : 0; //模型
            $user = Yii::$app->request->post('user') ? (int)Yii::$app->request->post('user') : 0; //当前用户
            $date = Yii::$app->request->post('date'); //查询时间

            //列表数据
            $projectUpageLog = new ProjectUpdateLog();
            $count = $projectUpageLog->getCount($projectId, $date, $module, $user, $type);
            $totalPage = ceil($count / $pageSize);
            //重设当前页
            if ($page < 1) {
                $page = 1;
            } elseif ($page > $totalPage) {
                $page = $totalPage;
            }
            $offset = ((int)$page - 1) * $pageSize;
            $list = $projectUpageLog->getList($projectId, $date, $module, $user, $type, $limit = $pageSize, $offset);
            $list = array_reverse($list);

            //分页数据
            $param = array(
                'total_rows' => $count,
                'list_rows' => $pageSize,
                'sub_pages' => 10,
                'page_name' => 'page',
                'now_page' => $page
            );
            $myPager = new MyPager($param);
            $pager = $myPager->contsruct_num_Page();

            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return Responses::response200(array('list' => $list, 'pager' => $pager, 'count' => $count), 'success', true);
        }
    }

    /*获取公开部门显示结果*/
    private function getAccessUsers($access, $accessStr)
    {
        switch ($access) {
            case 2:
                $access_users = (new UserModel())->getUserStr($accessStr);//可访问的用户str
                break;
            case 1:
                $access_users = '私密';
                break;
            default:
                $access_users = '公司全体人员';
                break;
        }
        return $access_users;
    }

}
